import AuthAPI from '../api/auth'
import BaseActionCableConnector from '@/yichat.web.share/helpers/BaseActionCableConnector'
import DashboardAudioNotificationHelper from './AudioAlerts/DashboardAudioNotificationHelper'
import { MESSAGE_TYPE } from '@/yichat.web.share/constants/messages'

class ActionCableConnector extends BaseActionCableConnector {
  constructor (app, pubsubToken) {
    const { websocketURL = '' } = window.chatwootConfig || {}
    super(app, pubsubToken, websocketURL)
    this.CancelTyping = []
    this.events = {
      'message.created': this.onMessageCreated,
      'message.updated': this.onMessageUpdated,
      'conversation.created': this.onConversationCreated,
      'conversation.status_changed': this.onStatusChange,
      'user:logout': this.onLogout,
      'page:reload': this.onReload,
      'assignee.changed': this.onAssigneeChanged,
      'conversation.typing_on': this.onTypingOn,
      'conversation.typing_off': this.onTypingOff,
      'conversation.contact_changed': this.onConversationContactChange,
      'presence.update': this.onPresenceUpdate,
      'contact.deleted': this.onContactDelete,
      'contact.updated': this.onContactUpdate,
      'conversation.mentioned': this.onConversationMentioned,
      'notification.created': this.onNotificationCreated,
      'first.reply.created': this.onFirstReplyCreated,
      'conversation.read': this.onConversationRead,
      'conversation.updated': this.onConversationUpdated,
    }
  }

  isAValidEvent = data => {
    return this.app.$store.getters.getCurrentAccountId === data.accountId
  }

  onMessageUpdated = data => {
    this.app.$store.dispatch('updateMessage', data)
  }

  onPresenceUpdate = data => {
    this.app.$store.dispatch('contacts/updatePresence', data.contacts)
    this.app.$store.dispatch('agents/updatePresence', data.users)
    this.app.$store.dispatch('setCurrentUserAvailability', data.users)
  }

  onConversationContactChange = payload => {
    const { meta = {}, id: conversationId } = payload
    const { sender } = meta || {}
    if (conversationId) {
      this.app.$store.dispatch('updateConversationContact', {
        conversationId,
        ...sender,
      })
    }
  }

  onAssigneeChanged = payload => {
    const { id } = payload
    if (id) {
      this.app.$store.dispatch('updateConversation', payload)
    }
    this.fetchConversationStats()
  }

  onConversationCreated = data => {
    this.app.$store.dispatch('addConversation', data)
    this.fetchConversationStats()
  }

  onConversationRead = data => {
    this.app.$store.dispatch('updateConversation', data)
  }

  onLogout = () => AuthAPI.logout()

  onMessageCreated = data => {
    DashboardAudioNotificationHelper.onNewMessage(data)
    this.app.$store.dispatch('addMessage', data)
  }

  onReload = () => window.location.reload()

  onStatusChange = data => {
    this.app.$store.dispatch('updateConversation', data)
    this.fetchConversationStats()
  }

  onConversationUpdated = data => {
    this.app.$store.dispatch('updateConversation', data)
    this.fetchConversationStats()
  }

  onTypingOn = ({ conversation, user }) => {
    const conversationId = conversation.id

    this.clearTimer(conversationId)
    this.app.$store.dispatch('conversationTypingStatus/create', {
      conversationId,
      user,
    })
    this.initTimer({ conversation, user })
  }

  onTypingOff = ({ conversation, user }) => {
    const conversationId = conversation.id

    this.clearTimer(conversationId)
    this.app.$store.dispatch('conversationTypingStatus/destroy', {
      conversationId,
      user,
    })
  }

  onConversationMentioned = data => {
    this.app.$store.dispatch('addMentions', data)
  }

  clearTimer = conversationId => {
    const timerEvent = this.CancelTyping[conversationId]

    if (timerEvent) {
      clearTimeout(timerEvent)
      this.CancelTyping[conversationId] = null
    }
  }

  initTimer = ({ conversation, user }) => {
    const conversationId = conversation.id
    // Turn off typing automatically after 30 seconds
    this.CancelTyping[conversationId] = setTimeout(() => {
      this.onTypingOff({ conversation, user })
    }, 30000)
  }

  fetchConversationStats = () => {
    bus.$emit('fetch_conversation_stats')
    bus.$emit('fetch_overview_reports')
  }

  onContactDelete = data => {
    this.app.$store.dispatch(
      'contacts/deleteContactThroughConversations',
      data.id
    )
    this.fetchConversationStats()
  }

  onContactUpdate = data => {
    this.app.$store.dispatch('contacts/updateContact', data)
  }

  onNotificationCreated = data => {
    this.app.$store.dispatch('notifications/addNotification', data)
  }

  onFirstReplyCreated = () => {
    bus.$emit('fetch_overview_reports')
  }
}

export default {
  init (pubsubToken) {
    return new ActionCableConnector(window.WOOT, pubsubToken)
  },
}
